package com.naraba.socket.protocolnetty;

import com.naraba.socket.netty.FirstClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @auther xjl
 * @date 2020/10/30
 * @description
 **/
public class NettyClient {
    public static void main(String[] args) {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap
                .group(workGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ClientHandler()   );
                    }
                });
//        bootstrap.connect("127.0.0.1", 8000).addListener(fucture -> {
//           if (fucture.isSuccess()) {
//               System.out.println("连接成功!");
//           }else {
//               System.out.println("连接失败!");
//
//           }
//        });
        connect(bootstrap, "127.0.0.1", 8000, MAX_RETRY);
    }

    private static  int MAX_RETRY = 5;
    private static void connect(Bootstrap bootstrap, String host, int port, int retry) {
        bootstrap.connect(host, port)
                .addListener(future -> {
                    if (future.isSuccess()) {
                        System.out.println("连接成功！");
                    }else if (retry == 0) {
                        System.out.println("重试次数已用完，放弃连接！");
                    }else {
                        // 第几次重连
                        int order = (MAX_RETRY - retry) +1;
                        // 本次重连的间隔，1<<order 相当于1乘以2的order次方
                        int delay = 1 << order;
                        System.out.println(new Date() + ": 连接失败，第" + order + "次重连……");
                        bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry -1), delay,
                                TimeUnit.SECONDS);
                    }
                });
    }
}
